# ===============================================================================================================
#    ReallyPreventStandby - a plugin for Squeezebox Server 7.5 and greater
#
#    Prevents the system (Windows, Linux/Gnome, OSX) from sleeping while music is playing.
#
#    Version 20110307.102347
#
#    Copyright (C) 2010 Gordon Harris
#
#    This program is free software; you can redistribute it and/or
#    modify it under the terms of the GNU General Public License,
#    version 2.
#
#	 Settings.pm -- adapted from /Slim/plugin/PreventStandby/Settings.pm
#

package Plugins::ReallyPreventStandby::Settings;


use strict;
use base qw(Slim::Web::Settings);
use Slim::Utils::Prefs;

# Global vars
use Plugins::ReallyPreventStandby::Plugin;
use vars qw(%g);
*g = \%Plugins::ReallyPreventStandby::Plugin::g;
#my %g = %Plugins::ReallyPreventStandby::Plugin::g;
#my $g = ${%Plugins::ReallyPreventStandby::Plugin::g};

sub new {
	my $class = shift;
	
	#Initialize the log..
	initLog();
	
	#Initialize the prefs..
	initPrefs();
	
	$g{log}->is_debug && $g{log}->debug("Settings initialized..");
	
	$class->SUPER::new;
}

sub initLog {
	
	if (!defined( $g{log} )) {
		$g{log} = Slim::Utils::Log->addLogCategory({
			'category'     => 'plugin.ReallyPreventStandby',
			'defaultLevel' => 'ERROR',
			'description'  => 'PLUGIN_REALLYPREVENTSTANDBY',
			});
		$g{log}->is_debug && $g{log}->debug("Log initialized..");
	}
}


sub initPrefs {
	
	if (!defined( $g{prefs} )) {
		$g{prefs} = preferences('plugin.reallypreventstandby');
	}
	
	#Initialize the defaults..
	#Plugins::ReallyPreventStandby::Plugin::initPrefDefaults();
	
	#Read the prefs file..
	$g{log}->is_debug && $g{log}->debug("Reading prefs..");
	readPrefs();

	$g{prefs}->migrate(1, sub { 
		# this download is used to count the number of installs of the plugin, it only occurs once
		Slim::Networking::SimpleAsyncHTTP->new(sub {}, sub {})->get("http://srvrpowerctrl.googlecode.com/files/ReallyPreventStandby_counter");
		1;
	});
	
	#Migrate the prefs...this will set any defaults if they don't exist..
	$g{prefs}->migrate(2, \&_migratePrefs);

	#Regularize our prefs..
	$g{log}->is_debug && $g{log}->debug("Regularizing Prefs..");
	_fixupPrefs();
	
	#Set the validations..
	Plugins::ReallyPreventStandby::Plugin::setPrefValidations();

	#set our prefs change handler..
	$g{log}->is_debug && $g{log}->debug("Setting Prefs change handler..");
	$g{prefs}->setChange(\&_prefsChange, (GetPrefNames()) );

	#Report our prefs..
	_dispPrefs();

	$g{log}->is_debug && $g{log}->debug("Prefs initialized..");

	return defined($g{prefs});	
	
}


sub readPrefs {
	foreach my $prefname (GetPrefNames()) {
		$g{prefs}->{$prefname} = $g{prefs}->get($prefname);
		#$g{log}->is_debug && $g{log}->debug("$prefname == $g{prefs}->{$prefname}");
	}
}


sub _migratePrefs {

	$g{log}->debug("Migrating prefs..");

	#Check for stale or missing prefs..reset to defaults if necessary..
	#If the plugin version is > than the prefs file version, reset all the prefs to defaults.
	if ( !$g{prefs}->{nPrefsVersion} || $g{prefs}->{nPrefsVersion} < $g{nAppVersion} ) {
		_setPrefDefaults( 0 );
		readPrefs();
	}

	$g{log}->debug("Prefs migrated..");
	return 1;
}

sub _setPrefDefaults {
	my $bForce = shift;


	$g{log}->info("Setting prefs to $g{nAppVersion} defaults");
	$g{prefs}->set('nPrefsVersion', $g{nAppVersion} );
	
	$g{prefDefaults} = Plugins::ReallyPreventStandby::Plugin::initPrefDefaults();

	#Write the default values to the prefs file..
	while ( my ($pref, $default) = each(%{$g{prefDefaults}}) ) {
		if ($bForce) {
			$g{prefs}->set( $pref, $default );
		}
		#Don't overwrite the prefs if they're defined...
		elsif ( ! defined($g{prefs}->get($pref)) ) {
			$g{prefs}->set( $pref, $default );
		}

    }
}


#Fixup undefined prefs values to "" or 0
sub _fixupPrefs {
	foreach my $prefname (GetPrefNames()) {
		if ( !defined($g{prefs}->$prefname) ) {
			#Don't set string prefs to 0
			if ( substr($prefname,0,2) eq 'sz' ) {
				$g{prefs}->set($prefname, "");
			} else {
				$g{prefs}->set($prefname, 0);
			}
		} elsif ( $g{prefs}->$prefname eq 'on' ) {
			$g{prefs}->set($prefname, 1);
		}
	}
}


sub _dispPrefs {
	my $showpref = shift;
	my $msg = shift;
	my @pnames;
	my $num = 0;
	my $preflabel;

	if (defined($showpref)) {
		push (@pnames, $showpref);
	} else {
		@pnames = GetPrefNames();
	}

	if (!defined($msg)) {
		$msg = " ";
	} else {
		$msg = $msg . " ";
	}

	#get the length of the longest prefname
	foreach my $pref ( GetPrefNames() ) {
		if ($num < length($pref)) {
			$num = length($pref);
		}
	}
	foreach my $pref (@pnames) {
		$preflabel = sprintf('%*2$s', $pref, $num);
		$g{log}->debug("$msg $preflabel == $g{prefs}->{$pref}");
	}
}


sub _prefsChange {
	my ($pref, $value) = @_;
	
	#validate boolian prefs
	if ( substr($pref, 0, 1) eq 'b' ) {
		if (!defined($value)) {
			#fix up the reference to silence a warning in the log..
			$value = 0;
			@_[1] = 0;
			$g{prefs}->{$pref} = $value;
		} elsif ($value eq 'on') {
			$value = 1;
			@_[1] = 1;
			$g{prefs}->{$pref} = $value;
		}
	#validate numeric prefs: if the value is not a number, reset it to the default..
	} elsif ( substr($pref, 0, 1) eq 'n' ) {
		if (!IsNumeric($value)) {
			#$value = $prefDefaults{$pref};
			$value = $g{prefDefaults}->{$pref};
			@_[1] = $value;
			$g{prefs}->{$pref} = $value;
		}

	#Fixup any string values
	#} elsif ( substr($pref,0,2) eq 'sz' ) {
	#	if (!defined($value)) {
	#		#fix up the reference to silence a warning in the log..
	#		@_[1] = "";
	#		$value = "";
	#		$g{prefs}->{$pref} = $value;
	#	}
	#g{log}->debug("String translation: $g{prefs}->{$pref} vs. $value..");

	#define any other undefined values..
	} else {
		if (!defined($value)) {
			#fix up the reference to silence a warning in the log..
			$value = "";
			@_[1] = $value;
			$g{prefs}->{$pref} = $value;
		}
	}

	#special validations...
	Plugins::ReallyPreventStandby::Plugin::prefsChange();
	
	#$g{log}->is_debug && $g{log}->debug("$pref == $value");
	#_dispPrefs();
}


#Get the SqueezeCenter Version, change it from 7.3.4 form into 7.34 and make it numeric..
#LIMITATION: this would see 7.4.1 as equal to 7.4.10
sub GetSCVersion {
	my $nSCVersion = $::VERSION;
	if (length($nSCVersion) > 3) {
		my $szMinor = substr($nSCVersion, 3);
		#remove any periods..
		$szMinor =~ s/\.//g;
		$nSCVersion = substr($nSCVersion, 0, 3) . $szMinor;
	}

	$nSCVersion = $nSCVersion * 1;

	return $nSCVersion;
}


sub IsNumeric {
	my ($num) = @_;

	#$g{log}->debug("Testing $num");

	if (!defined($num)) {
		return 0;
 	} elsif ($num =~ /^-?\d/) {
		return 1;
	}
	return 0;
}


sub GetPrefNames {
	my @prefNames = ( );
	while ( my ($k, $v) = each(%{$g{prefDefaults}}) ) {
		push(@prefNames, $k);
    }
	return @prefNames;
}


#This adds the name to the Settings->Advanced combobox.
sub name {
	return Slim::Web::HTTP::CSRF->protectName('PLUGIN_REALLYPREVENTSTANDBY');
}


sub page {
	return Slim::Web::HTTP::CSRF->protectURI('plugins/ReallyPreventStandby/settings/basic.html');
}


sub prefs {
	return ($g{prefs}, (GetPrefNames()));
}


sub handler {
	my ($class, $client, $params) = @_;
	my $action;
	my $item;

	#$g{log}->debug("Settings page handler: params == $params");

	if ($params->{'reset'}) {
		$g{log}->is_debug && $g{log}->debug("Resetting prefs to default values..");

		#Initialize the defaults..
		$g{prefDefaults} = Plugins::ReallyPreventStandby::Plugin::initPrefDefaults();
		_setPrefDefaults( 1 );
		readPrefs();
		_dispPrefs();
	}

	return $class->SUPER::handler($client, $params);
}


1;

__END__
